package com.axiang.lib_common.network;

import androidx.annotation.NonNull;

import com.axiang.lib_api.http.retry.RetryFunction;
import com.axiang.lib_common.mvvm.model.BaseModel;
import com.axiang.lib_common.mvvm.viewmodel.BaseViewModel;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


public class ObserverUtil {

    /**
     * 线程调度
     * @param model
     * @param <T>
     * @return
     */
    public static <T> ObservableTransformer<T,T> schedulersTransformer(final BaseModel model){
        return new ObservableTransformer<T, T>() {
            @NonNull
            @Override
            public ObservableSource<T> apply(@NonNull Observable<T> upstream) {

                return upstream
                        .subscribeOn(Schedulers.io())
                        .retryWhen(new RetryFunction(3,3))
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                model.addSubscribe(disposable);
                            }
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread()); //指定observer回调在UI主线程中进行;
            }
        };
    }
}
